<template>
    <div>
        <table>
            <thead>
            <tr>
                <th>消息编号</th>
                <th>发送者</th>
                <th>发送时间</th>
                <th>发送内容</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="item in messageList" :key="item.time">
                <td>{{ item.id }}</td>
                <td>{{ item.username }}</td>
                <td>{{ new Date(item.time).toLocaleTimeString() }}</td>
                <td>{{ item.message }}</td>
            </tr>
            </tbody>
        </table>
        <input
                type="text"
                v-model="sendMessage"
                placeholder="请输入你要发送的消息">
        <button @click="handleSendButton">发送</button>
    </div>
</template>

<script setup>
    import {ref,onMounted,onBeforeUnmount} from "vue";
    //传入username
    const username1=ref('')
    const webSocketObject=ref()
    const messageList=ref([])
    const sendMessage=ref('')
    onMounted(()=>{
        username1.value="用户1"
        webSocketInit(username1)
    })
    onBeforeUnmount(()=>{
        webSocketObject.value.close();
    })
    const webSocketInit=(username)=>{
        const webSocketUrl = 'ws://localhost:8082/websocket/'+username.value
        webSocketObject.value = new WebSocket(webSocketUrl);
        webSocketObject.value.onopen = webSocketOnOpen
        webSocketObject.value.onmessage = webSocketOnMessage
        webSocketObject.value.onerror = webSocketOnError
        webSocketObject.value.onclose = webSocketOnClose
    }
    const webSocketOnOpen=(e)=>{
        console.log('与服务端连接打开->',e)
    }
    const webSocketOnMessage=(e)=>{
        console.log('来自服务端的消息->',e)
        const receiveMessage = JSON.parse(e.data);
        messageList.value.push(receiveMessage)
    }
    const webSocketOnError=(e)=>{
        console.log('与服务端连接异常->',e)
    }
    const webSocketOnClose=(e)=>{
        console.log('与服务端连接关闭->',e)
    }
    const handleSendButton=()=> {
        //orderId
        let username = username1.value
        //merchantId
        let message = sendMessage.value
        webSocketObject.value.send(JSON.stringify({
            id: 1,
            message,
            username,
            time: new Date().getTime()
        }))
        sendMessage.value = ''
    }
</script>

